package cn.rui.service.goods;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.rui.common.ContentBean;
import cn.rui.common.ResponseBean;
import cn.rui.mapper.goods.CategoryMapper;
import cn.rui.mapper.goods.GoodsMapper;
import cn.rui.pojo.goods.Category;
import cn.rui.pojo.goods.Goods;
import cn.rui.pojo.vo.PageVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @author 徽州大都督
 * @date 2021/6/21
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private GoodsMapper goodsMapper;

    public ResponseBean findAll() {
        List<Category> categories = categoryMapper.selectList (null);
        return ResponseBean.success (ContentBean.QuerySuccess, categories);
    }

    public ResponseBean findPage(PageVo pageVo) {
        QueryWrapper<Category> wrapper = new QueryWrapper<> ();
        Page<Category> page = new Page<> (pageVo.getCurrentPage (), pageVo.getPageSize ());

        if (StrUtil.isNotEmpty (pageVo.getQueryContent ())) {
            wrapper.like ("name", pageVo.getQueryContent ());
        }

        IPage<Category> categoryIPage = categoryMapper.selectPage (page, wrapper);

        PageVo pv = new PageVo ();

        pv.setTotal (categoryIPage.getTotal ());

        List<Category> categories = categoryIPage.getRecords ();

        pv.setData (categories);

        return ResponseBean.success (ContentBean.QuerySuccess, pv);
    }

    public ResponseBean deleteById(Long id) {

        QueryWrapper<Goods> wrapper = new QueryWrapper<> ();
        wrapper.eq ("category_id", id);
        List<Goods> goodsList = goodsMapper.selectList (wrapper);
        if (CollUtil.isNotEmpty (goodsList)) {
            return ResponseBean.error (ContentBean.DeleteError, 401);
        }
        categoryMapper.deleteById (id);
        return ResponseBean.success (ContentBean.DeleteSuccess);
    }

    public ResponseBean updateCategory(Category category) {
        category.setUpdateTime (new Date ());
        categoryMapper.updateById (category);
        return ResponseBean.success (ContentBean.UpdateSuccess);
    }

    public ResponseBean save(Category category) {
        categoryMapper.insert (category);
        return ResponseBean.success (ContentBean.SavaSuccess);
    }

}
